const express=require("express");
const md5=require("md5");
const handleDB=require("../db/handleDB");
const common=require("../utils/common");
const constant=require("../utils/constant");
// const upload_file=require("../utils/qn");
const keys = require("../keys");
const multer=require("multer");


const storage=multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'public/news/upload/avatar')
    },
    filename:function(req,file,cb){
        cb(null,file.originalname)
    }
})
const upload=multer({storage:storage})

const router=express.Router();

router.get("/profile",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let data={
            user_info:{
                nick_name:userInfo[0].nick_name,
                avatar_url:userInfo[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE+userInfo[0].avatar_url):"/news/images/worm.jpg"
            }
        }
        res.render("news/user",data)
    })();
})

router.all("/user/base_info",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        if(req.method==="GET"){
            let data={
                nick_name:userInfo[0].nick_name,
                signature:userInfo[0].signature,
                gender:userInfo[0].gender?userInfo[0].gender:"WOMAN"
            }
            res.render("news/user_base_info",data)
        }else if(req.method==="POST"){
            let {signature,nick_name,gender}=req.body
            if(!signature || !nick_name || !gender){
                res.send({errmsg:"参数错误"})
                return
            }

            await handleDB(res,"info_user","update","数据库更新数据出错",`id=${userInfo[0].id}`,{
                signature,
                nick_name,
                gender
            })

            res.send({errno:"0",errmsg:"操作成功"})
        }
    })();
})

router.all("/user/pass_info",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        if(req.method==="GET"){
            res.render("news/user_pass_info")
        }else if(req.method==="POST"){
            let {old_password,new_password,new_password2}=req.body
            if(!old_password || !new_password || !new_password2){
                res.send({errmsg:"参数错误"})
                return
            }

            if(new_password!==new_password2){
                res.send({errmsg:"两次密码不一致"})
                return
            }

            if(md5(md5(old_password)+keys.password_salt)!==userInfo[0].password_hash){
                res.send({errmsg:"旧密码不正确，修改失败"})
                return
            }

            await handleDB(res,"info_user","update","数据库更新数据出错",`id=${userInfo[0].id}`,{
                password_hash:md5(md5(new_password)+keys.password_salt)
            })

            res.send({errno:"0",errmsg:"操作成功"})
        }
    })();
})

router.get("/user/pic_info",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        res.render("news/user_pic_info")
    })();
})

router.post("/user/pic_info",upload.single("avatar"),(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let file=req.file

        // console.log(file)
        // try{
        //     var retObj=await upload_file(file.originalname,`${file.destination}/${file.filename}`)
        // }catch(error){
        //     res.send({errmsg:"上传七云牛失败"})
        //     return
        // }

        await handleDB(res,"info_user","update","数据库修改数据失败",`id=${userInfo[0].id}`,{
            avatar_url:file.originalname
        })

        let data={
            avatar_url:constant.QINIU_AVATAR_URL_PRE+file.originalname
        }

        res.send({errno:"0",errmsg:"上传成功",data})
    })();
})

router.get("/user/collections",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let {p=1}=req.query

        let currentPage=p;

        let counts=await handleDB(res,"info_user_collection","sql","数据库查询出错",`select count(*) from info_user_collection where user_id=${userInfo[0].id}`)

        let collectionNewsIdList=await handleDB(res,"info_user_collection","find","数据库查询错误2",`user_id=${userInfo[0].id} limit ${(currentPage-1)*10},10`);

        let collectionNewsList=[]

        for(var i=0;i<collectionNewsIdList.length;i++){
            let ret=await handleDB(res,"info_news","sql","数据库查询出错3",`select id,title,create_time from info_news where id=${collectionNewsIdList[i].news_id}`)
            ret[0].url=`/news_detail/${ret[0].id}`
            collectionNewsList.push(ret[0])
        }

        let totalPage=Math.ceil(counts[0]["count(*)"]/10);

        let data={
            currentPage,
            totalPage,
            collectionNewsList
        }
        res.render("news/user_collection",data)
    })();
})

router.get("/news/followed_user",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);  

        let {p=1}=req.query

        let currentPage=p;

        let fans=await handleDB(res,"info_user_fans","sql","数据库查询出错",`select count(*) from info_user_fans where follower_id=${userInfo[0].id}`)

        //关注列表followsIdList
        let followsIdList=await handleDB(res,"info_user_fans","find","数据库查询错误2",`follower_id=${userInfo[0].id} limit ${(currentPage-1)*4},4`);


        let followsList=[]
        for(var i=0;i<followsIdList.length;i++){
            //获取被关注作者的信息 图像、昵称、简介
            let authorInfo=await handleDB(res,"info_user","find","数据库查询出错3",`id=${followsIdList[i].followed_id}`);

            //获取被关注作者 发布文章的数量
            let authorWords=await handleDB(res,"info_news","sql","数据库查询出错4",`select count(*) from info_news where user_id=${authorInfo[0].id}`)

            //获取被关注作者 粉丝数量
            let authorFans=await handleDB(res,"info_user_fans","sql","数据库查询出错5",`select count(*) from info_user_fans where followed_id=${authorInfo[0].id}`)

            followsList[i]={
                authorInfo:{
                    id:authorInfo[0].id,
                    nick_name:authorInfo[0].nick_name,
                    signature:authorInfo[0].signature,
                    avatar_url:authorInfo[0].avatar_url?(constant.QINIU_AVATAR_URL_PRE+authorInfo[0].avatar_url):"/news/images/worm.jpg"

                },
                authorWords:authorWords[0]["count(*)"],
                authorFans:authorFans[0]["count(*)"]
            }

        }

        console.log(followsList)
        let totalPage=Math.ceil(fans[0]["count(*)"]/4);

        let data={
            currentPage,
            totalPage,
            followsList

        }
        res.render("news/user_follow",data)
    })();
})

router.post("/news/followed_user",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);  

        let {user_id,action}=req.body;
        if(!user_id || !action){
            res.send({errmsg:"参数错误1"})
            return
        }

        let userResult=await handleDB(res,"info_user","find","数据库查询出错",`id=${user_id}`);
        if(!userResult[0]){
            res.send({errmsg:"参数错误2"})
            return
        }

        if(action==="unfollow"){
            await handleDB(res,"info_user_fans","delete","数据库删除失败",`follower_id=${userInfo[0].id} and followed_id=${user_id}`)
        }
        res.send({errno:"0",errmsg:"操作成功"});
    })();
})

router.get("/user/news_release",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let categorysIdList=await handleDB(res,"info_category","sql","数据库查询错误2",`select id,name from info_category`);

        let categorysList=[]
        for(var i=1;i<categorysIdList.length;i++){
            let ret=await handleDB(res,"info_category","sql","数据库查询出错3",`select id,name from info_category where id=${categorysIdList[i].id}`)

            categorysList.push(ret[0])
        }

        let data={
            categorysList
        }
        res.render("news/user_news_release",data)
    })();
})

router.post("/user/news_release",upload.single("index_image"),(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);
        let file=req.file
        let {title,category_id,digest,content}=req.body

        console.log(req.body)

        await handleDB(res,"info_news","insert","数据库插入数据失败",{
            title,
            source:'未知',
            digest,
            content,
            category_id,
            index_image_url:constant.QINIU_AVATAR_URL_PRE+file.originalname,
            user_id:userInfo[0].id
        })
        

        res.send({errno:"0",errmsg:"上传成功"})
    })();
})

router.get("/user/news_list",(req,res)=>{
    (async function(){
        let userInfo=await common.getUserInfo(req,res);

        let {p=1}=req.query

        let currentPage=p;

        let counts=await handleDB(res,"info_news","sql","数据库查询出错",`select count(*) from info_news where user_id=${userInfo[0].id}`)

        let authorNewsIdList=await handleDB(res,"info_news","find","数据库查询错误2",`user_id=${userInfo[0].id} limit ${(currentPage-1)*10},10`);

        let authorNewsList=[]

        for(var i=0;i<authorNewsIdList.length;i++){
            let ret=await handleDB(res,"info_news","sql","数据库查询出错3",`select title,create_time from info_news where id=${authorNewsIdList[i].id}`)
            ret[0].url=`/news_detail/${authorNewsIdList[i].id}`
            authorNewsList.push(ret[0])
        }

        let totalPage=Math.ceil(counts[0]["count(*)"]/10);

        let data={
            currentPage,
            totalPage,
            authorNewsList
        }
        res.render("news/user_news_list",data)
    })();
})
module.exports=router